Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

695
Vistas
React/Jest - How to simulate touch "swipe" event

I have a component that triggers a function call whenever a swipe interaction was done. This swipe interaction can either be executed by touchEvent or mouseEvent. My goal was to check if the function was called, whenever a swipe occured. But I fail to simulate the touchEvent in a jest test. Using swiper, react, react-testing-library and jest.

Online Editor link for testing: Codesandbox

The actual class

const App = ({ funcCalledOnSlideChange }) => {
  return (
    <Swiper
      pagination={{
        clickable: true
      }}
      modules={[Pagination]}
      watchOverflow
      onSlideChange={funcCalledOnSlideChange}
    >
      <SwiperSlide>
        <img className="slide" />
      </SwiperSlide>
      <SwiperSlide>
        <img className="slide-second" />
      </SwiperSlide>
    </Swiper>
  );
};

And the actual test

const mockFunc = jest.fn();

function sendTouchEvent({ x, y, element, eventType }) {
  const touchObj = new Touch({
    identifier: Date.now(),
    target: element,
    clientX: x,
    clientY: y,
    radiusX: 2.5,
    radiusY: 2.5,
    rotationAngle: 10,
    force: 0.5
  });

  const touchEvent = new TouchEvent(eventType, {
    cancelable: true,
    bubbles: true,
    touches: [touchObj],
    targetTouches: [],
    changedTouches: [touchObj]
  });

  element.dispatchEvent(touchEvent);
}

test("should swipe by touch event", async () => {
  const { container } = render(<App funcCalledOnSlideChange={mockFunc} />);
  const swiperSlide = container.querySelector(".swiper-slide");

  act(() => {
    sendTouchEvent({
      x: 350,
      y: 100,
      element: swiperSlide,
      eventType: "touchstart"
    });
    sendTouchEvent({
      x: 200,
      y: 100,
      element: swiperSlide,
      eventType: "touchmove"
    });
    sendTouchEvent({
      x: 150,
      y: 100,
      element: swiperSlide,
      eventType: "touchend"
    });
  });

  await waitFor(() => {
    expect(mockFunc).toBeCalled();
  });
});

Actual error:

Failed to construct 'Touch': Failed to read the 'target' property from 'TouchInit': Failed to read the 'target' property from 'TouchInit': Required member is undefined.
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda